<template>
  <div class="app_content">
    <h4 class="form-header h4">基本信息</h4>
    <el-form ref="form" :model="formData" label-width="80px" :size="size">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="用户昵称" prop="nickName" >
            <el-input v-model="formData.nickName" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="登录账号" prop="userName" >
            <el-input  v-model="formData.userName" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <h4 class="form-header h4">角色信息</h4>
      <el-table :border="$border" v-loading="loading" :data="roles" :height="maxHeight"   style="width: 100%;" :row-key="getRowKey" @row-click="clickRow" ref="tableRef" @selection-change="handleSelectionChange"  :size="size"
      >
      <el-table-column type="selection" width="55" />
      <el-table-column label="编号" prop="id" show-overflow-tooltip key="id" >
        <template #default="scope">{{scope.$index+1}}</template>
        </el-table-column>
      <el-table-column label="角色名称" prop="roleName" show-overflow-tooltip key="roleName"  />
      <el-table-column label="权限字符" prop="roleKey" show-overflow-tooltip key="roleKey"  />
      <el-table-column label="显示顺序" prop="roleSort" show-overflow-tooltip key="roleSort"  />
      <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip key="createTime"  />
  </el-table>
  <div style="margin-top:10px;position: absolute;right: 0;margin-right:20px">
      <el-pagination
        v-model:currentPage="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  </div>
  <div style="height: 40px;margin: 0px auto;width: 160px;margin-top: 75px;">
    <el-button type="primary" @click="submitForm()" :size="size">
      <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-correct'"/>
      提交</el-button>
    <el-button @click="close()" :size="size">
      <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-return'"/>
      返回</el-button>
  </div>
  
  </div>
  
</template>

<script  >
import { getAuthRole, updateAuthRole } from "@/api/system/user";
import { computed, ref ,reactive,onMounted,getCurrentInstance,toRefs, nextTick} from 'vue'
import { useStore } from 'vuex';
import {useRoute,useRouter} from 'vue-router';
import {
} from '@element-plus/icons-vue'

export default defineComponent({
  components:{
  },
setup(){
  const { proxy } = getCurrentInstance();//关键代码
  const store = useStore();
  const route=useRoute()
  const router=useRouter()
  const tableRef=ref(null)
  const staticData=reactive({
    formData:{
     
    },
    maxHeight:store.getters['setting/mode']=='horizontal'?document.body.clientHeight - 390:store.getters['setting/isFullScreen']!=false ?document.body.clientHeight - 360:document.body.clientHeight - 420,
    single:true,
    multiple:true,
    background:false,
    disabled :false,
    // 查询参数
    queryParams: {
        pageNum: 1,
        pageSize: 10,
       
    },
    roles:[],
    roleIds:[],
    total:0,
    loading:true, 
   
  })
  const size = computed(() => {
        return store.getters['setting/size'];
  });
  const small =computed(() => {
    return size.value=='small'?true:false
  });

  const visitedRouteList = computed(() => {
        return store.getters['tabsBar/visitedRoutes'];
  });

  const isActive = (route) => {
        return route.path === router.currentRoute.value.path;
      };
    const toLastTag = (latestView) => {
        
        if (latestView) {
          router.push(latestView);
        } else {
          router.push('/');
        }
      };

      const handleTabRemove = async (data) => {
        let view;
        visitedRouteList.value.forEach((item) => {
          if (data.activePath == item.path) {
            view = item;
          }
        });
        
        const { visitedRoutes } = await store.dispatch('tabsBar/delRoute', view);
        if (isActive(view)) {
          toLastTag(data.tarPath);
        }
      };
 
  onMounted(() => {
    const userId = route.query.userId;
      proxy.getList(userId)
    })

  const methods = {
     getList(userId){
      
      if (userId) {
        staticData.loading = true;
        getAuthRole(userId).then((response) => {
          staticData.formData = response.user;
          staticData.roles = response.roles;
          staticData.total = staticData.roles.length;
          nextTick(() => {
            staticData.roles.forEach((row) => {
              if (row.flag) {
                tableRef.value.toggleRowSelection(row);
              }
            });
          });
          staticData.loading = false;
        });
      }
     },
     /** 单击选中行数据 */
    clickRow(row) {
      tableRef.value.toggleRowSelection(row);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      staticData.roleIds = selection.map((item) => item.roleId);
    },
    // 保存选中的数据编号
    getRowKey(row) {
      return row.roleId;
    },
    /** 提交按钮 */
    submitForm() {
      const userId = staticData.formData.userId;
      const roleIds = staticData.roleIds.join(",");
      updateAuthRole({ userId: userId, roleIds: roleIds }).then((response) => {
        proxy.Success("授权成功");
        proxy.close();
      });
    },
    /** 关闭按钮 */
    close() {
      let data={
        activePath:'/system/user-role',
        tarPath:'/system/user'
      }
      handleTabRemove(data)
    },
    
    handleSizeChange (val) {
      console.log(`${val} items per page`)
      staticData.queryParams.pageSize =val;
      proxy.getList()
    },
    handleCurrentChange(val){
      console.log(`current page: ${val}`)
      staticData.queryParams.pageNum =val;
      proxy.getList()
    }
   }
    return {
      size,
      small,
      tableRef,
      ...methods,
      ...toRefs(staticData)
    }
}


})



</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
margin-top: 10px;
}
.demo-pagination-block .demonstration {
margin-bottom: 16px;
}
</style>
<style scoped>
.app_content{
  
  margin-top: 30px;
  margin-left: 10px;
}
.mb8{
  margin-bottom: 10px;
}
.tree-border {
    margin-top: 5px;
    width: 100%;
    border: 1px solid #e5e6e7;
    background: #fff none;
    border-radius: 4px;
}
</style>